package com.aiatomic.countlib;

import android.content.Context;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

class TplInitService {

    private TplInitService(){}

    public static void init(Context context){
        Object init = SPUtils.get(context, "init", false);
        if (init != null && (boolean) init) {
            return;
        }
        copy(context,"tpl_2001_1001");
        copy(context,"tpl_2004_1001");
        copy(context,"tpl_2005_1006");
        copy(context,"tpl_2006_1001");
        SPUtils.put(context, "init", true);
    }

    private static void copy(Context context,String assetPath) {
        try {
            String[] list = context.getAssets().list(assetPath);
            if (list == null) {
                return;
            }
            File dir = new File(context.getExternalCacheDir(), "/" + assetPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            for (String path : list) {
                File destFile = new File(dir, path);
                if (destFile.exists() && destFile.isDirectory()) {
                    throw new IOException("Destination '" + destFile + "' exists but is a directory");
                } else {
                    InputStream inputStream = context.getAssets().open(assetPath + "/" + path);
                    try {
                        FileOutputStream output = new FileOutputStream(destFile);
                        try {
                            IOUtils.copy(inputStream, output);
                        } finally {
                            IOUtils.closeQuietly(output);
                        }
                    } finally {
                        IOUtils.closeQuietly(inputStream);
                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
